<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Proxy</title>
</head>
<body>
    <input type="text" name="" id="input">
    <div id="model">321</div>
    <input type="text" name="" id="model-input">
    <script>

        let gd = (id) => {
            return document.getElementById(id)
        }

        // 双向绑定
        let input = gd('input')
        let model = gd('model')
        let modelInput = gd('model-input')

        let o = {
            name: '石兴龙'
        }
        let p = new Proxy(o, {
            // 代理: 获取属性
            get: (target, key) => {
                console.log('proxy get')
                return target[key]
            },
            // 代理: 属性设置
            set: (target, key, val) => {
                console.log('proxy set')

                input.value = val
                model.innerHTML = val
                modelInput.value = val

                return target[key] = val
            },
            // 代理: 删除 key
            deleteProperty: (target, key) => {
                return delete target[key]
            },
        })

        // 双向绑定
        /*const setEvent = function () {
            p.name = this.value
        }
        input.oninput = setEvent
        modelInput.oninput = setEvent*/

        p['name'] = 'test'
        console.log(p['name'])
        delete p.name
        console.log(o)

        // 撤销代理

        let obj = {
            name: '石兴龙'
        }
        let { proxy, revoke } = Proxy.revocable(obj, {
            // 代理: 获取属性
            get: (target, key) => {
                console.log('proxy get')
                return target[key]
            },
            // 代理: 属性设置
            set: (target, key, val) => {
                console.log('proxy set')

                input.value = val
                model.innerHTML = val
                modelInput.value = val

                return target[key] = val
            },
            // 代理: 删除 key
            deleteProperty: (target, key) => {
                return delete target[key]
            },
            // 代理: key in obj 的操作
            has: (target, key) => {
                console.log(target, key)
                return true
            },
        })

        // proxy.name = 'test'
        // revoke()
        // proxy.name = 'test 1'

        console.log(
            'name' in proxy,
            'age' in proxy,
        )


    </script>
</body>
</html>